package com.lovo.invoicing.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lovo.invoicing.bean.BuyCartBean;
import com.lovo.invoicing.bean.GoodsBean;
import com.lovo.invoicing.mapper.BuyCartMapper;
import com.lovo.invoicing.service.IBuyCartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class BuyCartServiceImpl extends ServiceImpl<BuyCartMapper, BuyCartBean> implements IBuyCartService {
   @Autowired
   BuyCartMapper buyCartMapper;
    @Override
    @Transactional
    public void addIntoCart(GoodsBean goodsBean,int buyNo,int userId) {
        QueryWrapper qw =new QueryWrapper<>();
        qw.eq("fk_userId",userId);
        List<BuyCartBean> list = baseMapper.selectList(qw);
        for (BuyCartBean c : list) {
            if (c.getGoodsNo().equals(goodsBean.getGoodsNo())){
                BuyCartBean bc =   baseMapper.selectById(c.getBuycartId());
                bc.setBuyNo(bc.getBuyNo()+buyNo);
                baseMapper.updateById(bc);
                return;
            }
        }
        BuyCartBean b = new BuyCartBean();
        b.setGoodsName(goodsBean.getGoodsName());
        b.setGoodsBrand(goodsBean.getGoodsBrand());
        b.setGoodsNo(goodsBean.getGoodsNo());
        b.setBuyNo(buyNo);
        buyCartMapper.insertBuyCart(b,userId);
    }

    @Override
    @Transactional
    public void deleteBuyCart(int buyCartId) {
        baseMapper.deleteById(buyCartId);
    }

    @Override
    @Transactional
    public void updateBuyCart(BuyCartBean buyCartBean) {
        buyCartMapper.updateBuyCart(buyCartBean);
    }

    @Override
    @Transactional
    public void deleteAllBuyCart(int userId) {
        QueryWrapper qw =new QueryWrapper();
        qw.eq("fk_userid",userId);
        baseMapper.delete(qw);
    }

    @Override
    public List<BuyCartBean> queryBuyCarts(int userId) {
        QueryWrapper<BuyCartBean> qw =new QueryWrapper<>();
        qw.eq("fk_userId",userId);
        return baseMapper.selectList(qw);
    }
}
